<template>
  <div>
    <!-- 搜索和新增部分 -->
    <!-- <el-row class="search_content">
      <el-col :span="8">
        客户名:
        <el-input
          v-model.trim="userName"
          placeholder="请输入内容"
          :clearable="true"
          @keydown.enter.native="search"
          size="mini"
          maxlength="20"
        ></el-input>
      </el-col>
      <el-col :span="8">
        地址:
        <el-input
          v-model.trim="address"
          placeholder="请输入内容"
          :clearable="true"
          size="mini"
          @keydown.enter.native="search"
          maxlength="30"
        ></el-input>
      </el-col>
      <el-col :span="4">
        <template>
          @change选中值改变时触发事件
          <el-select
            v-model="type"
            placeholder="合作类型"
            :clearable="true"
            size="mini"
            @change="search"
          >
            <el-option
              v-for="(item, value) in types"
              :key="value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </template>
      </el-col>
      <el-col :span="2">
        <el-button
          size="mini"
          class="search_btn"
          type="primary"
          plain
          @click="search"
          >搜索</el-button
        ></el-col
      >
      <el-col :span="2">
        <el-button
          type="primary"
          @click="openAdd"
          class="fr add_btn"
          size="mini"
        >
          新增
        </el-button>
      </el-col>
    </el-row> -->
    <!-- 列表显示客户信息 -->
    <!-- 注selection-change为选择项改变时的事件 stripe为斑马纹 -->

    <!-- Modal -->
    <span class="h3">
      <i class="el-icon-user"></i>
       用户管理
    </span>

    <button
      type="button"
      class="btn btn-info btn-xs"
      data-toggle="modal"
      data-target="#myModal"
      style="margin:40px 0 0 0px"
    >
      新增
    </button>
    <button type="danger" class="btn btn-danger btn-xs" @click="batchDelete()" style="margin:40px 0 0 0px"
          >删除</button
        >
    <el-row type="flex" justify="center">
    <el-col :span="8">
    <div
      class="modal fade"
      id="myModal"
      tabindex="-1"
      role="dialog"
      aria-labelledby="myModalLabel"
    >
      <div class="modal-dialog" role="document" style="margin:50px auto;">
        <div class="modal-content">
          <div class="modal-header">
            <button
              type="button"
              class="close"
              data-dismiss="modal"
              aria-label="Close"
            >
              <span aria-hidden="true">&times;</span>
            </button>
            <div class="addform">
            <div style="background:#409eff">用户新增</div>
            <el-form
            :model="params"
            :rules="rules"
            ref="addUser"
            :label-position="labelPosition"
            label-width="100px"
          >
            <el-form-item label="账号" prop="account" style="margin-left:20px">
              <el-input
                placeholder="请输入账号"
                v-model.trim="params.account"
                :clearable="true"
                maxlength="20"
                style="width:80%"
              ></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password" style="margin-left:20px">
              <el-input
                placeholder="请输入密码"
                id="des_pwd"
                v-model="params.password"
                :clearable="true"
                maxlength="20"
                show-password
                style="width:80%"
              ></el-input>
              <el-button @click="creat_pwd" size="mini" type="text">随机密码</el-button>
            </el-form-item>
            <el-form-item label="确认密码" prop="aga_password" style="margin-left:20px">
              <el-input
                placeholder="请输入密码"
                v-model="params.aga_password"
                :clearable="true"
                maxlength="20"
                style="width:80%"
                id="des_pwd"
                show-password
              ></el-input>
            </el-form-item>
            <el-form-item label="用户名" prop="name" style="margin-left:20px">
              <el-input
                placeholder="请输入用户名"
                v-model="params.name"
                :clearable="true"
                maxlength="20"
                style="width:80%"
              ></el-input>
            </el-form-item>
            <el-form-item label="权限等级" prop="level" style="margin-left:20px">
              <el-select v-model="level" placeholder="请选择权限" :clearable="true" size="mini" >
          <el-option
            v-for="(item, value) in levels"
            :key="value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
            </el-form-item>
            <!-- <el-form-item label="合作类型" prop="type">
              <el-radio-group v-model="params.type">
                <el-radio :label="1">租出</el-radio>
                <el-radio :label="2">购入</el-radio>
              </el-radio-group>
            </el-form-item> -->
            <!-- <el-form-item>
              <el-button type="primary" @click="addUser('addUser')"
                >提交</el-button
              >
              <el-button @click="resetForm('addUser')">重置</el-button>
            </el-form-item> -->
          </el-form>
          </div>
          </div>
          <div class="modal-body">
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal" style="margin: 20px">
              关闭
            </button>
            <button type="button" class="btn btn-primary" style="margin: 20px"  @click="addUser('addUser')">提交</button>
          </div>
        </div>
      </div>
    </div>
    </el-col>
    </el-row>
    <el-table id="el-table" :data="lists" @selection-change="getIds" stripe>
      <el-table-column type="selection" width="55px"></el-table-column>
      <el-table-column label="id" prop="user_id"></el-table-column>
      <el-table-column label="账号" prop="account"></el-table-column>
      <el-table-column label="密码" prop="password"></el-table-column>
      <el-table-column label="姓名" prop="name"></el-table-column>
      <el-table-column label="权限等级" prop="level"></el-table-column>
      <el-table-column label="状态" prop="state">
        <template slot-scope="scope">
          <el-switch @click.native = "findOldUser(scope.row)"
              v-model="scope.row.state"
              :active-value="0"
              :inactive-value="1"
            ></el-switch>
        </template>
      </el-table-column>
    </el-table>
    <el-row type="flex" align="middle" id="bottom">
      <el-col :span="8" :push="6">
        <el-pagination
          @size-change="pageSizeChange"
          @current-change="currPageChange"
          :current-page="curr_page"
          :page-sizes="[10, 20, 50, 100, 200]"
          :page-size="page_size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </el-col>
    </el-row>
    <div class="back top" @click="top" v-show="!gotop" title="go顶部">
      <i class="el-icon-arrow-up"></i>
    </div>
    <div class="back bottom" v-show="gotop" @click="bottom" title="go底部">
      <i class="el-icon-arrow-down"></i>
    </div>
    <el-row>
      <!-- 用户新增抽屉 -->
      <el-drawer
        title="用户新增"
        :visible.sync="isShow"
        size="24%"
        direction="rtl"
      >
        <div class="addform">
          <el-form
            :model="params"
            :rules="rules"
            ref="addUser"
            :label-position="labelPosition"
            label-width="80px"
          >
            <el-form-item label="客户名" prop="user_name">
              <el-input
                placeholder="请输入客户名"
                v-model.trim="params.user_name"
                :clearable="true"
                maxlength="20"
              ></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input
                placeholder="请输入手机号"
                v-model="params.phone"
                :clearable="true"
                maxlength="11"
              ></el-input>
            </el-form-item>
            <el-form-item label="地址" prop="address">
              <el-input
                placeholder="请输入地址"
                v-model.trim="params.address"
                :clearable="true"
                maxlength="30"
              ></el-input>
            </el-form-item>
            <el-form-item label="合作类型" prop="type">
              <el-radio-group v-model="params.type">
                <el-radio :label="1">租出</el-radio>
                <el-radio :label="2">购入</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="addUser('addUser')"
                >提交</el-button
              >
              <el-button @click="resetForm('addUser')">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-drawer>
    </el-row>
    <el-row>
      <el-drawer
        title="用户修改"
        :visible.sync="updateShow"
        size="25%"
        direction="rtl"
      >
        <div class="addform">
          <el-form
            :model="params"
            :rules="rules"
            ref="updateUser"
            :label-position="labelPosition"
            label-width="80px"
          >
            <el-form-item label="客户名" prop="address">
              <el-input
                :disabled="true"
                placeholder="请输入客户名"
                v-model.trim="params.user_name"
                :clearable="true"
                maxlength="20"
              ></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input
                placeholder="请输入手机号"
                v-model.trim="params.phone"
                :clearable="true"
                maxlength="11"
              ></el-input>
            </el-form-item>
            <el-form-item label="地址" prop="address">
              <el-input
                placeholder="请输入地址"
                v-model.trim="params.address"
                :clearable="true"
                maxlength="30"
              ></el-input>
            </el-form-item>
            <el-form-item label="合作类型" prop="type">
              <el-radio-group v-model="params.type">
                <el-radio :label="1">租出</el-radio>
                <el-radio :label="2">购入</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="updateUser('updateUser')"
                >提交</el-button
              >
              <el-button @click="resetForm('updateUser')">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-drawer>
    </el-row>
    <!-- Button trigger modal -->

    <!-- Modal -->
  </div>
</template>

<script>
import http from '@/utils/httpUtil'
import aes from '@/utils/AESUtil.js'
import pinyin from '../../../node_modules/js-pinyin/index'
export default {
  data () {
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.params.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      direction: 'rtl',
      drawer: false,
      labelPosition: 'left',
      formLabelAlign: {
        name: '',
        region: '',
        type: ''
      },
      gotop: true,
      isShow: false,
      updateShow: false,
      action: {
        userList: 'ssmService/user/selectPageUser',
        addUser: 'ssmService/user/addUser',
        updateUser: 'ssmService/user/updateUser',
        selectUserById: 'ssmService/user/selectUserById',
        deleteUser: 'ssmService/user/deleteUser'
      },
      level: '',
      levels: [
        {
          label: '超级管理员',
          value: 1
        },
        {
          label: '管理员',
          value: 2
        },
        {
          label: '员工',
          value: 3
        }
      ],
      lists: [],
      permission: [],
      total: 0,
      page_size: 10,
      curr_page: 1,
      type: '',
      types: [
        {
          label: '租出',
          value: 1
        },
        {
          label: '购入',
          value: 2
        }
      ],
      address: '',
      userName: '',
      params: {
        account: '',
        password: '',
        aga_password: '',
        name: '',
        level: ''
      },
      rules: {
        account: [
          {
            required: true,
            message: '请输入客户名',
            trigger: 'blur'
          },
          {
            pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9]+$/,
            message: '请输入正确的格式'
          }
        ],
        name: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          },
          {
            pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9]+$/,
            message: '请输入正确的格式'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }
        ],
        aga_password: [
          {
            // required: true,
            validator: validatePass2,
            trigger: 'blur'
          }
        ]
      },
      ids: ''
    }
  },
  mounted () {
    this.getUserList()
  },
  methods: {
    creat_pwd () {
      var pwd_length = Math.round(Math.random() * 20)
      var new_pwd = ''
      var j = 0
      var char = 'ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890-\\/.!@#$%^&()_'
      for (var i = 0; i < parseInt(pwd_length); i++) {
        j = Math.floor(Math.random() * char.length)
        new_pwd += char.charAt(j)
        console.log(new_pwd)
      }
      // document.getElementById('des_pwd').innerHTML = new_pwd
      this.params.password = new_pwd
      this.params.aga_password = new_pwd
    },
    top () {
      document.getElementById('top').scrollIntoView()
    },
    bottom () {
      document.getElementById('bottom').scrollIntoView(false)
    },
    // 当前页总条数改变时函数
    pageSizeChange (pageSize) {
      this.getUserList(this.address, this.userName, this.type, 1, pageSize)
    },
    // 当前页改变时函数
    currPageChange (currPage) {
      this.getUserList(
        this.address,
        this.userName,
        this.type,
        currPage,
        this.page_size
      )
    },
    // 获取用户列表
    getUserList (
      address = null,
      userName = null,
      type = null,
      curr_page = 1,
      page_size = 10
    ) {
      const params = {
        curr_page: curr_page,
        page_size: page_size
      }
      if (address !== null && address !== '') {
        params['address'] = address
      }
      if (userName !== null && userName !== '') {
        params['user_name'] = userName
      }
      if (type !== null && type !== '') {
        params['type'] = type
      }
      http.xhrGet(this, this.action.userList, params, res => {
        // 总条数，当前页，当前页最大条数，数据
        this.total = res.data.total
        this.curr_page = res.data.pageNum
        this.page_size = res.data.pageSize
        this.lists = res.data.list
      })
    },
    search () {
      let address = this.address
      address = address.replace(/(^\s*)|(\s*$)/g, '')
      let user_name = this.userName
      user_name = user_name.replace(/(^\s*)|(\s*$)/g, '')
      let type = this.type
      this.getUserList(
        pinyin.getFullChars(address),
        pinyin.getFullChars(user_name),
        type,
        1,
        10
      )
    },
    // 新增客户
    openAdd () {
      this.isShow = true
      this.params = {
        account: '',
        password: '',
        aga_password: '',
        name: '',
        level: 1
      }
    },
    resetForm (refName) {
      this.$refs[refName].resetFields()
    },
    addUser (refName) {
      this.$refs[refName].validate(valid => {
        if (valid) {
          // 将汉字转为拼音
          // this.params.py_address = pinyin.getFullChars(this.params.address)
          // console.log(this.params.py_address)
          // this.params.py_user_name = pinyin.getFullChars(this.params.user_name)
          this.params.level = this.level
          const params = this.params
          params['baseModel.token'] = aes.getRandom(16, 16)
          // console.log(params)
          // 发送数据给服务器，实现新增功能
          http.xhrPost(this, this.action.addUser, params, res => {
            // console.log(res)
            // 给出提示，新增成功，关闭抽屉，刷新页面，清空表单
            this.$message({
              type: 'success',
              message: res.message
            })
            this.isShow = false
            this.getUserList()
            // 表单重置
            this.params = {
              user_name: '',
              address: '',
              phone: '',
              type: 1
            }
          })
        } else {
          return false
        }
      })
    },
    // 实现修改
    updateUser (refName) {
      this.$refs[refName].validate(valid => {
        if (valid) {
          // const params = {}
          // Object.keys(this.params).forEach(key => {
          //   console.log(key)
          //   params['user.' + key] = this.params[key]
          // })
          this.params['baseModel.token'] = aes.getRandom(16, 16)
          // 发送修改请求
          http.xhrPost(this, this.action.updateUser, this.params, res => {
            this.$message({
              type: 'success',
              message: res.message
            })
            this.params = {
              user_name: '',
              address: '',
              phone: '',
              type: 1
            }
            this.updateShow = false
            // 刷新指定页
            this.getUserList(
              this.address,
              this.userName,
              this.type,
              this.curr_page,
              this.page_size
            )
          })
        } else {
          return false
        }
      })
    },
    // 将旧数据回显到页面上
    findOldUser (user) {
      // console.log(user)
      this.updateShow = true
      // console.log(res.data)
      // 根据userid取出最新的用户数据，因为version版本必须是最新的
      const param = {
        user_id: user.user_id
      }
      http.xhrGet(this, this.action.selectUserById, param, res => {
        console.log(res)
        this.params.user_name = res.data[0].user_name
        this.params.phone = res.data[0].phone
        this.params.address = res.data[0].address
        this.params.type = res.data[0].type
        this.params.version = res.data[0].version
        this.params.user_id = res.data[0].user_id
      })
    },
    batchDelete () {
      if (this.ids !== '') {
        this.$confirm('您正在执行批量操作，是否继续', '提示', {
          confirmButtonText: '确认执行',
          cancelButtonText: '容我想想'
        })
          .then(() => {
            let ids = this.ids.substring(0, this.ids.length - 1)
            this.xhrDelete(ids)
          })
          .catch(() => {})
      } else {
        this.$message({
          type: 'error',
          message: '请至少选中一条'
        })
      }
    },
    // 得到所有的id
    getIds (users) {
      console.log(users)
      this.ids = ''
      users.forEach((item, index) => {
        this.ids += item.user_id + ','
      })
    },
    delUser (users) {
      // 询问用户是否删除
      this.$confirm('您确定要删除当前记录吗?', '确定删除?', {
        confirmButtonText: '残忍丢弃',
        cancelButtonText: '容我想想'
      })
        .then(() => {
          // 发送删除请求
          this.xhrDelete(users.user_id)
        })
        .catch(() => {})
    },
    xhrDelete (ids) {
      // 发送真实删除请求
      http.xhrPost(this, this.action.deleteUser + '/' + ids, null, res => {
        this.$message({
          type: 'success',
          message: res.message
        })
        this.getUserList(
          this.address,
          this.userName,
          this.type,
          this.curr_page,
          this.page_size
        )
      })
    }
  },
  components: {
    indexHeader1: () => import('@/components/indexHeader')
  },
  // 过滤器
  filters: {
    formatDate (value) {
      // 时间戳转换日期格式方法
      if (value == null) {
        return ''
      } else {
        let date = new Date(value)
        let y = date.getFullYear() // 年
        let MM = date.getMonth() + 1 // 月
        MM = MM < 10 ? '0' + MM : MM
        let d = date.getDate() // 日
        d = d < 10 ? '0' + d : d
        let h = date.getHours() // 时
        h = h < 10 ? '0' + h : h
        let m = date.getMinutes() // 分
        m = m < 10 ? '0' + m : m
        let s = date.getSeconds() // 秒
        s = s < 10 ? '0' + s : s
        return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s
      }
    }
  }
}
</script>

<style scoped>
@import "../../assets/css/reset.css";
@import "../../assets/css/client.css";
</style>
